package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.sky.exception.BaseException;
import lombok.Data;

import java.util.HashMap;

public class BaiduUtil {

    private static final String GEOCODING_URL = "https://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=%s";

    @Data
    public static class GeoResponse{
        private int status;
        private GeoResult result;
    }

    @Data
    public static class GeoResult{
        private GeoPoint location;
        private Integer precise;
        private Integer confidence;
        private Integer comprehension;
        private String level;
    }

    @Data
    public static class GeoPoint {
        private double lat;
        private double lng;
    }

    /**
     * {"status":0,"result":{"location":{"lng":117.00439910401157,"lat":36.65755167364164},"precise":0,"confidence":20,"comprehension":24,"level":"区县"}}
     * */
    public static final GeoPoint getGeoPoint(String address, String ak){
        String url = String.format(GEOCODING_URL, address, ak);
        String json = HttpClientUtil.doGet(url, new HashMap<>());
        GeoResponse geoResponse = JSON.parseObject(json, GeoResponse.class);
        if(geoResponse.getStatus() == 0){
            return geoResponse.getResult().getLocation();
        }
        throw new BaseException("调用百度地图API获取经纬度异常");
    }

}
